package com.kunchi.platform.controller;

import com.kunchi.platform.model.data.CurrentData;
import com.kunchi.platform.model.data.HistoryData;
import com.kunchi.platform.service.DataService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by denniszhou on 2017/6/24.
 */
@Controller
@RequestMapping(value = "/data")
public class DataController {
    @Autowired
    DataService dataService;

    @RequestMapping(value = "/current")
    public List<CurrentData> getCurrentData(
            @RequestParam(name = "device_id") String deviceId,
            @RequestParam(name = "dataitem_id", required = false) String dataItemId,
            @RequestParam(name = "dataitem_name", required = false) String dataItemName) throws IOException {
        Stream<CurrentData> stream = dataService.getCurrentData(deviceId).stream();
        if (!StringUtils.isEmpty(dataItemId)) {
            stream = stream.filter(s -> s.getItemid().equals(dataItemId));
        }
        if (!StringUtils.isEmpty(dataItemName)) {
            stream = stream.filter(s -> s.getItemname().equals(dataItemName));
        }
        return stream.collect(Collectors.toList());
    }

    @RequestMapping(value = "/history", method = RequestMethod.GET)
    public HashMap<String, List<HistoryData>> getHistoryData(
            @RequestParam(name = "device_id") String deviceId,
            @RequestParam(name = "start_time", required = false) Long startTimestamp,
            @RequestParam(name = "end_time", required = false) Long endTimestamp) throws IOException {
        return dataService.getHistoryData(deviceId, startTimestamp, endTimestamp);
    }

    @RequestMapping(value = "/history/dataitem")
    public List<HistoryData> getHistoryDataByDataItemId(
            @RequestParam(name = "device_id") String deviceId,
            @RequestParam(name = "dataitem_id") String dataItemId,
            @RequestParam(name = "start_time", required = false) Long startTimestamp,
            @RequestParam(name = "end_time", required = false) Long endTimestamp) throws IOException {
        return dataService.getHistoryDataByDataItemId(deviceId, dataItemId, startTimestamp, endTimestamp);
    }
}
